package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.Permission;
import cn.tedu.knows.portal.model.Role;
import cn.tedu.knows.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper mapper;
    //当前类需要保存到Spring容器里@Compent不能少
    //需要基于Spring-Security设计的方法进行登录 实现UserDetailsService接口
    //下面方法是接口提供的,我们来实现方法的参数是用于在登录表单编写的用户名
    //方法的返回值是UserDetails类型,这个类型对象包含登录需要的用户名密码权限等
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1,根据用户名查询用户对象
        User user = mapper.findUserByUsername(username);
        //2,判断是否能查询到用户,没有表示用户名不存在
        if (user==null){
            return null;
        }
        //3,根据用户id查询用户权限
        List<Permission> permissions = mapper.findUserPermissionById(user.getId());
        //4,将权限的集合转换为String类型数组,并赋值
        String[] auth = new String[permissions.size()];
        int i = 0;
        for (Permission p :permissions){
            auth[i] = p.getName();
            i++;
        }

        //查询当前用户所有角色
        List<Role> roles = mapper.findUserRolesById(user.getId());
        //数组扩容
        auth= Arrays.copyOf(auth,auth.length+roles.size());
        for (Role role :
                roles) {
            auth[i] = role.getName();
            i++;
        }
        //5,构建UserDetails对象
        UserDetails details = org.springframework.security.core
                .userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                //设定当前账户是否锁定  布尔值
                .accountLocked(user.getLocked()==1)
                //设置当前账户是否可用
                .disabled(user.getEnabled()==0)
                .build();

        //6,返回UserDetails对象
        return details;
    }
}
